package environment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import data.Logger;

/**
 * Whiteboard class, used for
 * - Goal location, simulated by goalKnown boolean value
 * - Storing success rate for each round
 * 
 * @author Toar
 */
public class Whiteboard 
{	
	private static HashMap<String, Integer> sr;
	public static boolean goalKnown = false;
	
	public static void init()
	{
		sr = new HashMap<String, Integer>();
	}
	
	public static int getSuccessRate(String s)
	{
		if(sr.containsKey(s))
			return sr.get(s);
		return 0;
	}
	
	public static void incrementSuccessRate(String s)
	{
		if(sr.containsKey(s))
		{
			sr.put(s, sr.get(s) + 1);
		}
		else
		{
			sr.put(s, 1);
		}
	}
	
	public static void decrementSuccessRate(String s)
	{
		if(sr.containsKey(s))
		{
			sr.put(s, sr.get(s) - 1);
		}
		else
		{
			sr.put(s, -1);
		}
	}
	
	public static void printHistory()
	{
		ArrayList<String> a = new ArrayList<String>();
		for(String s : sr.keySet())
		{
			a.add(s);
		}
		Collections.sort(a);
		for(String s : a)
		{
			/** fix so that we may have more than 1 digit robot & box ID */
			int bIndex = s.indexOf("b");
			Logger.log("Robot " + s.substring(0, bIndex) + 
					" successfully pushed box " + s.substring(bIndex) + 
					" " + sr.get(s) + " times.");
		}
	}
	
	/**
	 * Checks if there exists a dominator for a given box, and success rate
	 * The dominator cannot be the sender robot
	 * @param boxID
	 * @param success
	 * @return
	 */
	public static boolean existsDominator(String senderID, String boxID, int success)
	{
		for(String s : sr.keySet())
		{
			if(!s.startsWith(senderID) && s.endsWith(boxID))
			{
				int numSuccess = Whiteboard.getSuccessRate(s);
				if(numSuccess > success)
				{
					//System.out.println(s + " DOMINATES: " + numSuccess);
					return true;
				}
			}
		}
		return false;
	}
	
	
	public static boolean isDominator(String robotID, String boxID, int success)
	{
		String key = robotID + boxID;
		int numSuccess = Whiteboard.getSuccessRate(key);
		return numSuccess > success;
	}
}
